//
//  UITextView+Emoticon.swift
//  Emoticon
//
//  Created by 袁航 on 15/8/6.
//  Copyright © 2015年 yuanhang. All rights reserved.
//

import UIKit
extension UITextView {
    
    // 根据图表插入属性文字
    func insertEmoticon(emoticon: Emoticons) {
        // 判断是否是删除按钮,如果是删除按钮,删除上一个文字
        if emoticon.remove {
            // 删除光标前面的文字
            deleteBackward()
            return
        }
        // 输入emoji图片
        if emoticon.emoji != nil {
            replaceRange(selectedTextRange!, withText: emoticon.emoji!)
            return
        }
        // 拼接属性字符串
        let attach = EmoticonAttachment()
        attach.chs = emoticon.chs
        attach.image = UIImage(contentsOfFile: emoticon.pngImagePath)
        let attrStrM = NSMutableAttributedString(attributedString: NSAttributedString(attachment: attach))
        let textH = font!.lineHeight
        attach.bounds = CGRect(x: 0, y: -4, width: textH, height: textH)
        // 设置拼接的属性字符串的文本属性
        attrStrM.addAttribute(NSFontAttributeName, value: font!, range: NSMakeRange(0, 1))
        // 获取textView的属性字符串
        let textAttr = NSMutableAttributedString(attributedString: attributedText)
        textAttr.replaceCharactersInRange(selectedRange, withAttributedString: attrStrM)
        // 记录光标位置
        let range = selectedRange
        // 重新给textView赋值
        attributedText = textAttr
        // 复位光标
        selectedRange = NSMakeRange(range.location + 1, 0)
        // 主动调用代理方法
        if let del = delegate where del.respondsToSelector("textViewDidChange:"){
            del.textViewDidChange!(self)
        }
        
    }
    
    // 发送的字符串
    var emoticonText: String {
        // 获取textView的字符串
        let attStr = attributedText
        // 定义发送字符串
        var strM: String = String()
        attStr.enumerateAttributesInRange(NSMakeRange(0, attStr.length), options: NSAttributedStringEnumerationOptions(rawValue: 0)) { (dict, range, _) -> Void in
            // 判断是否存在Attachment
            if let str = dict["NSAttachment"] as? EmoticonAttachment {
                strM += str.chs!
            } else {
                let str = (attStr.string as NSString).substringWithRange(range)
                strM += str
            }
        }
        return strM
    }
}
